﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;

namespace Xbrowser
{

    public class HttpEventArgs
    {
        public string Command { get; }
        public object Data { get; }
        public HttpEventArgs(string command, object data) { Command = command; Data = data; }
 
    }

    public delegate void HttpEventHandler(object sender, HttpEventArgs e);

    internal class HttpListener {

        public event HttpEventHandler? OnRequest;
        IWebHost? host;

        public  void Start()
        {
            Thread thread = new Thread(() =>
            {
                Run();
            });
            thread.Start();
        }

        public void Stop()
        {
            if(host!= null)
            {
                host.StopAsync();
            }
        }

        public void Run()
        {
            int port = 2023;
            host = new WebHostBuilder().UseKestrel((options) => {
                options.ListenLocalhost(port);
            }).Configure(app => {
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = new PhysicalFileProvider(Environment.CurrentDirectory),
                    RequestPath = "/static"
                });
                app.Run(RequestDelegate);

            }).Build();

            host.Run();
        }

        private  Task RequestDelegate(HttpContext context)
        {
            try
            {
                if(context.Request.Method == "POST")
                {
                    string command = context.Request.Path;
                    string data = context.Request.Form["data"];
                    OnRequest?.Invoke(this, new HttpEventArgs(command, data));
                    context.Response.Headers.AccessControlAllowOrigin = "*";
                    context.Response.WriteAsync(command);
                }

                return Task.CompletedTask;

            }
            catch (Exception ex)
            {
                return Task.FromException(ex);
            }
        }
    }
}
